﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using Estimate.Common;
using Estimate.Common.Repository;
using Estimate.Common.DataFileFinder;
using Estimate.Common.DataFileCopyer;
using Estimate.Common.Estimate;
using Estimate.Common.Entity;
using Estimate.Common.DBFieldTypes;
using Estimate.Common.Memcached;
using Estimate.Common.DBHealth;
using Estimate.Common.OldEstimate;
using System.Windows.Forms;
using System.Threading;
using OperateLogLibrary;

namespace ManualTools
{
   public class OperateTools
    {
      public static OperateLog Log;
      public static  TextBox txtLog
      {
          set
          {
              Log = new OperateLog(value);
          }
          get
          {
              return Log.LogTextBox;
          }
      }
      public static ArchiveSystem.ShowBusy.Busy busy;
     

      delegate void Callback(TextBox txtLog,string msg);
      public static void SetLog(TextBox txtLog, string msg)
      {
          
          if (txtLog.Parent.InvokeRequired)
          {
              Callback cb = new Callback(SetLog);
              txtLog.Parent.Invoke(cb, new object[] { txtLog, msg });
              return;
          }

          txtLog.AppendText(msg);
          txtLog.SelectionStart = txtLog.Text.Length;
          txtLog.ScrollToCaret();
          txtLog.Focus();
      }

      public static void ImportData(DateTime date)
      {
          try
          {
              SetLog(txtLog, "\r\n导入预报、实况数据【" + DateTime.Now.ToString() + "】\r\n");
              DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);
              importer.Execute(date);
              SetLog(txtLog, "\r\n成功导入预报、实况数据【" + DateTime.Now.ToString() + "】\r\n");
             SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
          }
          catch (Exception ex)
          {
              busy.Hide();
              MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
             SetLog(txtLog,"\r\n预报、实况数据导入出错【" + DateTime.Now.ToString() + "】\r\n");
             SetLog(txtLog,"\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
             SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
          }
      }

      public static void ImportSchedule(int start_year, int start_month, int end_year, int end_month, bool forceClear)
      {
          try
          {
              SetLog(txtLog, "\r\n导入排班表数据【" + DateTime.Now.ToString() + "】\r\n");
              DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);
              importer.ImportSchedule(start_year, start_month, end_year, end_month, forceClear);
              SetLog(txtLog, "\r\n成功导入排班表数据【" + DateTime.Now.ToString() + "】\r\n");
             SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
          }
          catch (Exception ex)
          {
              busy.Hide();
              MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
             SetLog(txtLog,"\r\n排班表数据导入出错【" + DateTime.Now.ToString() + "】\r\n");
             SetLog(txtLog,"\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
             SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
          }

      }

      public static void ImportManualData(int start_year, int start_month, int end_year, int end_month, bool resemi)
      {
          try
          {
              SetLog(txtLog, "\r\n导入人工站数据【" + DateTime.Now.ToString() + "】\r\n");
              DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);
              importer.ImportManualData(start_year, start_month, end_year, end_month, resemi);
              SetLog(txtLog, "\r\n成功人工站数据【" + DateTime.Now.ToString() + "】\r\n");
             SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
          }
          catch (Exception ex)
          {
              busy.Hide();
              MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
             SetLog(txtLog,"\r\n人工站导入出错【" + DateTime.Now.ToString() + "】\r\n");
             SetLog(txtLog,"\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
             SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
          }


      }

      public static void ImportRealData(DateTime start, DateTime end, bool culsemi)
      {
          try
          {
              SetLog(txtLog, "\r\n导入自动站数据【" + DateTime.Now.ToString() + "】\r\n");
              DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);
              importer.Log = Log;
              importer.ImportRealData(start, end, culsemi);
              SetLog(txtLog, "\r\n成功导入自动站数据【" + DateTime.Now.ToString() + "】\r\n");
             SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
          }
          catch (Exception ex)
          {
              busy.Hide();
              MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
             SetLog(txtLog,"\r\n自动站导入出错【" + DateTime.Now.ToString() + "】\r\n");
             SetLog(txtLog,"\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
             SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
          }
         

      }

      public static void ReCalSemi(DateTime start, DateTime end)
      {
          try
          {
              SetLog(txtLog, "\r\n重新计算指导站Semi【" + DateTime.Now.ToString() + "】\r\n");
              DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);
              importer.Log = Log;
              importer.ReCalSemi(start, end, ConfigurationManager.AppSettings["ConnectionString"],
                                 new List<ForeRepository>() { ForeRepositoryFactory.StSiteForeRepository(ConfigurationManager.AppSettings["ConnectionString"]) });

              SetLog(txtLog, "\r\n成功重新计算指导站Semi【" + DateTime.Now.ToString() + "】\r\n");
             SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
          }
          catch (Exception ex)
          {
              busy.Hide();
              MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
             SetLog(txtLog,"\r\n重新计算指导站Semi出错【" + DateTime.Now.ToString() + "】\r\n");
             SetLog(txtLog,"\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
             SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
          }

         

      }

       //public static void ReImportSiteFore(DateTime start, DateTime end)
       // {
       //     try
       //     {
       //         SetLog(txtLog, "\r\n重新入库指导报数据【" + DateTime.Now.ToString() + "】\r\n");
       //         DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);
       //         importer.Log = OperateTools.Log;
       //         importer.CompleteSiteFore(start, end);
       //         SetLog(txtLog, "\r\n成功重新入库指导报数据【" + DateTime.Now.ToString() + "】\r\n");
       //        SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
       //     }
       //     catch (Exception ex)
       //     {
       //         busy.Hide();
       //         MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
       //        SetLog(txtLog,"\r\n指导报数据数据重新入库出错【" + DateTime.Now.ToString() + "】\r\n");
       //        SetLog(txtLog,"\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
       //        SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
       //     }

            
       // }

       //public static void ReImportCityFore(DateTime start, DateTime end)
       // {
       //     try
       //     {
       //         OperateTools.Log.SetLog( "\r\n重新入库城镇报数据");
       //         DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);
       //         importer.Log = OperateTools.Log;
       //         importer.CompleteCityFore(start, end);
       //         SetLog(txtLog, "重新入库城镇报数据操作结束");
       //         OperateTools.Log.SetLog("====================================================================");
       //     }
       //     catch (Exception ex)
       //     {
       //         busy.Hide();
       //         MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
       //         OperateTools.Log.SetLog("城镇报数据数据成功重新入库出错");
       //         OperateTools.Log.SetLog("错误信息：\r\n" + ex.ToString());
       //         OperateTools.Log.SetLog("====================================================================");
       //     }

           
       // }

       //public static void ReImportZytFore(DateTime start, DateTime end)
       // {
       //     try
       //     {
       //         SetLog(txtLog, "\r\n重新入库国家局数据【" + DateTime.Now.ToString() + "】\r\n");
       //         DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);
       //         importer.Log = OperateTools.Log;
       //         importer.CompleteZytFore(start, end);
       //         SetLog(txtLog, "\r\n成功重新入库国家局数据【" + DateTime.Now.ToString() + "】\r\n");
       //        SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
       //     }
       //     catch (Exception ex)
       //     {
       //         busy.Hide();
       //         MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
       //        SetLog(txtLog,"\r\n国家局数据数据成功重新入库出错【" + DateTime.Now.ToString() + "】\r\n");
       //        SetLog(txtLog,"\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
       //        SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
       //     }
           
       // }

       //public static void ReImportAccuFore(DateTime start, DateTime end)
       //{
       //    try
       //    {
       //        SetLog(txtLog, "\r\n重新入库Accu数据【" + DateTime.Now.ToString() + "】\r\n");
       //        DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);
       //        importer.Log = OperateTools.Log;
       //        importer.CompleteAccuFore(start, end);
       //        SetLog(txtLog, "\r\n成功重新入库Accu数据【" + DateTime.Now.ToString() + "】\r\n");
       //        SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
       //    }
       //    catch (Exception ex)
       //    {
       //        busy.Hide();
       //        MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
       //        SetLog(txtLog, "\r\nAccu数据数据重新入库出错【" + DateTime.Now.ToString() + "】\r\n");
       //        SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
       //        SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
       //    }

       //}

      public static void ReImportForeData(DateTime start, DateTime end, string tableName, string dirPath, string fileFilter, string description)
       {
           try
           {
               SetLog(txtLog, "\r\n重新入库【" + description + "】数据【" + DateTime.Now.ToString() + "】\r\n");
               DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);
               importer.Log = OperateTools.Log;
               importer.ReImportForeData(start, end, tableName, dirPath, fileFilter, description);
               SetLog(txtLog, "\r\n成功重新入库【" + description + "】数据【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
           }
           catch (Exception ex)
           {
               busy.Hide();
               MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
               SetLog(txtLog, "\r\n【" + description + "】数据数据重新入库出错【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
           }

       }

       public static void SaveMessage(string filename, string message)
        {
            FileStream fs = new FileStream(filename, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(message);
            sw.Flush();
            sw.Close();
        }

        /// <summary>
        /// 将某一天的实况数据从远端拷贝至本机
        /// </summary>
        /// <param name="dt"></param>
       public static void CopyDataFileForSingleDate(DateTime dt)
        {
            string[] pathList = null;
            IDataFileFinder finder;
            BaseDataFileCopyer copyer;

            string prefix = "";
            //远端机器上的 Normal_CityFore,RainFore,SiteFore数据会在第二天打包
            if (dt.Date.CompareTo(DateTime.Now.Date) == 0)
            {
                prefix = "Today_";
            }

            //城镇报、降水等值线、指导站过了当天后，数据都会备份至另外一个目录。所以当天的目录不同于往日的目录
            SetLog(txtLog, "\r\n拷贝 CityFore 文件【" + DateTime.Now.ToString() + "】\r\n");

            finder = new NormalCityForeFinder(); 
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings[prefix + "CityForeDirectory"]);
           SetLog(txtLog,"\r\n发现文件" + pathList.Length.ToString() + "个");
            copyer = DataFileCopyerFactory.NormalCityForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_CityForeDirectory"]);
            copyer.copyFiles(pathList);


            SetLog(txtLog, "\r\n拷贝 RainFore 文件【" + DateTime.Now.ToString() + "】\r\n");
            finder = new RainForeFinder();
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings[prefix + "RainForeDirectory_ZhongQi"]);
           SetLog(txtLog,"\r\n发现中期文件" + pathList.Length.ToString() + "个\r\n");
            copyer = DataFileCopyerFactory.RainForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_RainForeDirectory_ZhongQi"]);
            copyer.copyFiles(pathList);
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings[prefix + "RainForeDirectory_DuanQi"]);
           SetLog(txtLog,"\r\n发现短期文件" + pathList.Length.ToString() + "个\r\n");
            copyer = DataFileCopyerFactory.RainForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_RainForeDirectory_DuanQi"]);
            copyer.copyFiles(pathList);

            SetLog(txtLog, "\r\n拷贝 SiteFore 文件【" + DateTime.Now.ToString() + "】\r\n");
            finder = new SiteForeFinder();
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings[prefix + "StSiteForeDirectory"]);
           SetLog(txtLog,"\r\n发现短期文件" + pathList.Length.ToString() + "个\r\n");
            copyer = DataFileCopyerFactory.SiteForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_StSiteForeDirectory"]);
            copyer.copyFiles(pathList);
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings[prefix + "StSiteForeDirectory_Zhongqi"]);
           SetLog(txtLog,"\r\n发现中期文件" + pathList.Length.ToString() + "个\r\n");
            copyer = DataFileCopyerFactory.SiteForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_StSiteForeDirectory_Zhongqi"]);
            copyer.copyFiles(pathList);


            SetLog(txtLog, "\r\n拷贝 Zyt 文件【" + DateTime.Now.ToString() + "】\r\n"); ;
            finder = new ForeDataFilesFinder();
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings["ZytCityForeDirectory"]);
           SetLog(txtLog,"\r\n发现文件" + pathList.Length.ToString() + "个\r\n");
            copyer = DataFileCopyerFactory.ZytCityForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_ZytCityForeDirectory"]);
            copyer.copyFiles(pathList);

            SetLog(txtLog, "\r\n拷贝 User SiteFore 文件【" + DateTime.Now.ToString() + "】\r\n");
            finder = new UserSiteForeFinder();
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings["UserSiteForeDirectory"]);
           SetLog(txtLog,"\r\n发现文件" + pathList.Length.ToString() + "个\r\n");
            copyer = DataFileCopyerFactory.UserSiteForeCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_UserSiteForeDirectory"]);
            copyer.copyFiles(pathList);

            SetLog(txtLog, "\r\n拷贝 AutoReal 文件【" + DateTime.Now.ToString() + "】\r\n");
            finder = new AutoStationFinder();
            pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings["AutoStationDirectory"]);
           SetLog(txtLog,"\r\n发现文件" + pathList.Length.ToString() + "个\r\n");
            copyer = DataFileCopyerFactory.AutoStationCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_AutoStationDirectory"]);
            copyer.copyFiles(pathList);


            if (dt.Day == Convert.ToInt32(ConfigurationManager.AppSettings["ManualImportDate"]))
            {
                SetLog(txtLog, "\r\n符合配置指定的日期 " + ConfigurationManager.AppSettings["ManualImportDate"] + " ,拷贝 ManaulReal 文件【" + DateTime.Now.ToString() + "】\r\n");
                finder = new ManualStationFinder();
                pathList = finder.GetFileFromDirectory(dt, ConfigurationManager.AppSettings["ManualStationDirectory"]);
                System.Console.WriteLine("发现文件" + pathList.Length.ToString() + "个\r\n");
                copyer = DataFileCopyerFactory.ManualStationCopyer(ConfigurationManager.AppSettings["Copy_Directory_Root"] + ConfigurationManager.AppSettings["Copy_ManualStationDirectory"]);
                copyer.copyFiles(pathList);
                
            }

           SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
        }

       /// <summary>
       /// 预报员个人数据入库
       /// </summary>
       /// <param name="start"></param>
       /// <param name="end"></param>
       public static void ReImportForecasterFore(DateTime start, DateTime end)
        {
            DataImporterCombiner importer = new DataImporterCombiner(ConfigurationManager.AppSettings);
            importer.Log = OperateTools.Log;
            importer.CompleteForecasterForeLackFile(start, end, true);
        }

       public static void ReCalculateSemi(DateTime start, DateTime end)
        {
            try
            {
                SetLog(txtLog, "\r\n重新计算预报站Semi【" + DateTime.Now.ToString() + "】\r\n");
                DataImporterCombiner combiner = new DataImporterCombiner(ConfigurationManager.AppSettings);
                combiner.Log = OperateTools.Log;
                combiner.ReCalSemi(start, end, ConfigurationManager.AppSettings["ConnectionString"]);
                SetLog(txtLog, "\r\n成功重新计算预报站Semi【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
            }
            catch (Exception ex)
            {
                busy.Hide();
                MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
               SetLog(txtLog,"\r\n重新计算预报站Semi出错【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog,"\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
               SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
            }

           
        }


       public static void CheckScheduleRight(int startYear, int startMonth, int endYear, int endMonth)
        {
            try
            {
                SetLog(txtLog, "\r\n检查排班表数据【" + DateTime.Now.ToString() + "】\r\n");

                string connectionString = ConfigurationManager.AppSettings["ConnectionString"];

                DateTime start = new DateTime(startYear, startMonth, 1);
                DateTime end = new DateTime(endYear, endMonth, 1).AddMonths(1).AddDays(-1);
                IDataFileFinder finder = new ScheduleFinder();

                AffiliationRepository affiliationRepository = new AffiliationRepository(connectionString);
                AffiliationEntity[] affiliations = affiliationRepository.GetStationLevel(5);

                ScheduleHealth healthChecker = new ScheduleHealth(connectionString);
                DateTime cur = start;


                while (cur <= end)
                {

                    foreach (AffiliationEntity entity in affiliations)
                    {
                        if (entity.code == "00001")
                            continue;
                        healthChecker.IsHealth(cur, entity.code);
                    }

                    cur = cur.AddDays(1);
                }

                SetLog(txtLog, "\r\n成功检查排班表数据【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
            }
            catch (Exception ex)
            {
                busy.Hide();
                MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
               SetLog(txtLog,"\r\n排班表数据检查出错【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog,"\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
               SetLog(txtLog,"\r\n====================================================================\r\n\r\n\r\n\r\n");
               
            }

           
        }

       public static DataTable CheckForeRepositoryHealth(DateTime beginDate, DateTime endDate, string dataTable, string description, ForeSemiType semiType, ForeFactorType factorType,
                                                         bool CheckLackRecord, bool CheckEmptySemi, bool CheckValue, bool CheckSemi, bool CheckRepeatStation,
                                                         bool CheckLackStation, bool CheckAbnormalStation)
        {
            //ForeRepository repository = null;
            string msg = "";
           
            try
            {
                msg += description;
                switch (factorType)
                {
                    case ForeFactorType.wth:
                        msg += "天气要素";
                        break;
                    case ForeFactorType.maxt:
                        msg += "最高温";
                        break;
                    case ForeFactorType.mint:
                        msg += "最低温";
                        break;
                }
                if (semiType == ForeSemiType.Auto)
                    msg += "自动站数据";
                else
                    msg += "人工站数据";


                SetLog(txtLog, "\r\n检查" + msg + "【" + DateTime.Now.ToString() + "】\r\n");
                ForeHealth health = new ForeHealth();
                health.CheckLackRecord = CheckLackRecord;
                health.CheckEmptySemi = CheckEmptySemi;
                health.CheckValue = CheckValue;
                health.CheckSemi = CheckSemi;
                health.CheckRepeatStation = CheckRepeatStation;
                health.CheckLackStation = CheckLackStation;
                health.CheckAbnormalStation = CheckAbnormalStation;
                DataTable dt = health.CheckHealth(beginDate, endDate, semiType, factorType, dataTable);
                dt.TableName = msg + "检查结果(" + beginDate.ToString("yyyyMMdd") + "-" + endDate.ToString("yyyyMMdd") + ")";
                string dir = ConfigurationManager.AppSettings["ForeDataCheckResult_Directory"];
                CreateDirectory(dir);
                string filename = string.Format("{0}{1} {2} {3}_{4}.xml", msg , "检查结果", DateTime.Today.ToString("yyyyMMdd"), DateTime.Now.Hour.ToString(), DateTime.Now.Minute.ToString());
                dt.WriteXml(dir + "\\" + filename);
                SetLog(txtLog, "\r\n成功检查" + msg + "【" + DateTime.Now.ToString() + "】\r\n");
                SetLog(txtLog, "\r\n检查结果请查看\"" + dir + "\\" + filename + "\"【" + DateTime.Now.ToString() + "】\r\n");
                SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
                if (dt.Rows.Count == 0)
                {
                    busy.Hide();
                    MessageBox.Show("没有发现任何问题！", "提示！", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                return dt;
            }
            catch (Exception ex)
            {
                if (ex is ThreadAbortException)
                    SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
                else
                {
                    if (busy != null ) busy.Hide();
                    MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    SetLog(txtLog, msg + "检查出错【" + DateTime.Now.ToString() + "】\r\n");
                    SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
                    SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
                }

                return null;
            }

        }

       public static DataTable CheckRealRepositoryHealth(DateTime beginDate, DateTime endDate, RealDataType dataType,
                                                        bool CheckLackRecord, bool CheckEmptyValue, bool CheckValue, bool CheckRepeatStation,
                                                        bool CheckLackStation, bool CheckAbnormalStation)
       {
           //ForeRepository repository = null;
           string msg = "";
           try
           {

               switch (dataType)
               {
                   case RealDataType.auto_rain:
                       msg = "自动站降水实况数据";
                       break;
                   case RealDataType.manual_rain:
                       msg = "人工站降水实况数据";
                       break;
                   case RealDataType.auto_temp:
                       msg = "自动站温度实况数据";
                       break;
                   case RealDataType.manual_temp:
                       msg = "人工站温度实况数据";
                       break;
               }
  
               SetLog(txtLog, "\r\n检查" + msg + "【" + DateTime.Now.ToString() + "】\r\n");
               RealHealth health = new RealHealth();
               health.CheckLackRecord = CheckLackRecord;
               health.CheckEmptyValue = CheckEmptyValue;
               health.CheckValue = CheckValue;
               health.CheckRepeatStation = CheckRepeatStation;
               health.CheckLackStation = CheckLackStation;
               health.CheckAbnormalStation = CheckAbnormalStation;
               DataTable dt = health.CheckHealth(beginDate, endDate, dataType);
               dt.TableName = msg + "检查结果(" + beginDate.ToString("yyyyMMdd") + "-" + endDate.ToString("yyyyMMdd") + ")";
               string dir = ConfigurationManager.AppSettings["ForeDataCheckResult_Directory"];
               CreateDirectory(dir);
               string filename = string.Format("{0}{1} {2} {3}_{4}.xml", msg, "检查结果", DateTime.Today.ToString("yyyyMMdd"), DateTime.Now.Hour.ToString(), DateTime.Now.Minute.ToString());
               dt.WriteXml(dir + "\\" + filename);
               SetLog(txtLog, "\r\n成功检查" + msg + "【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n检查结果请查看\"" + dir + "\\" + filename + "\"【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
               if (dt.Rows.Count == 0)
               {
                   busy.Hide();
                   MessageBox.Show("没有发现任何问题！", "提示！", MessageBoxButtons.OK, MessageBoxIcon.Information);
               }
               return dt;
           }
           catch (Exception ex)
           {
               if (ex is ThreadAbortException)
                   SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
               else
               {
                   if (busy != null) busy.Hide();
                   MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   SetLog(txtLog, msg + "检查出错【" + DateTime.Now.ToString() + "】\r\n");
                   SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
                   SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
               }

               return null;
           }

       }


       public static void CompareSemi(string table, ForeSemiType semitype, DateTime beginDate, DateTime endDate)
        {
            string oldConnectionString = ConfigurationManager.AppSettings["OldConnectionString"];
            string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
            ForeRepository repository = ForeRepositoryFactory.NormalCityForeRepository(connectionString);
            switch (table)
            {
                case "site":
                    repository = ForeRepositoryFactory.StSiteForeRepository(connectionString);
                    break;
                case "city":
                    repository = ForeRepositoryFactory.NormalCityForeRepository(connectionString);
                    break;
                case "zyt":
                    repository = ForeRepositoryFactory.ZytCityForeRepository(connectionString);
                    break;

            }

            DateTime curDateTime = beginDate;
            while (curDateTime <= endDate)
            {
                EstimateChecker.CheckDayForeRecord(oldConnectionString, repository, curDateTime, semitype);
                curDateTime = curDateTime.AddDays(1);
            }

        }

       public static void ImportHomeReportData(List<string> kinds)
       {
           try
           {
               SetLog(txtLog, "\r\n生成首页报表数据【" + DateTime.Now.ToString() + "】\r\n");
               Estimate.Reports.AutoImportHomeReportData ImportHomeReportData = new Estimate.Reports.AutoImportHomeReportData(ConfigurationManager.AppSettings["ConnectionString"]);
               ImportHomeReportData.AddHomeReportData(kinds);
               SetLog(txtLog, "\r\n成功生成首页报表数据【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
           }
           catch (Exception ex)
           {
               if (ex is ThreadAbortException)
                   SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
               else
               {
                   busy.Hide();
                   MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   SetLog(txtLog, "\r\n生成首页报表数据出错【" + DateTime.Now.ToString() + "】\r\n");
                   SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
                   SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
               }

           }
       }

       public static void DeleHomeReportData(DateTime beginDate,DateTime endDate)
       {
           try
           {
               SetLog(txtLog, "\r\n删除首页报表数据【" + DateTime.Now.ToString() + "】\r\n");
               HomeReportRepository repository = new HomeReportRepository(ConfigurationManager.AppSettings["ConnectionString"]);
               repository.Delete(beginDate, endDate);
               SetLog(txtLog, "\r\n成功删除首页报表数据【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
           }
           catch (Exception ex)
           {
               if (ex is ThreadAbortException)
                   SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
               else
               {
                   busy.Hide();
                   MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   SetLog(txtLog, "\r\n删除首页报表数据出错【" + DateTime.Now.ToString() + "】\r\n");
                   SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
                   SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
               }
           }

       }

       public static void ImportForecasterRankData(int BeginYear, int BeginMonth, int EndYear, int EndMonth)
       {
           try
           {
               SetLog(txtLog, "\r\n生成预报员排名数据【" + DateTime.Now.ToString() + "】\r\n");
               Estimate.Reports.AutoImportForecasterRankReportData import = new Estimate.Reports.AutoImportForecasterRankReportData(ConfigurationManager.AppSettings["ConnectionString"]);
               import.AddForecasterRankReportData(BeginYear, BeginMonth, EndYear, EndMonth);
               SetLog(txtLog, "\r\n成功生成省台预报员排名数据【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
           }
           catch (Exception ex)
           {
               if (ex is ThreadAbortException)
                   SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
               else
               {
                   busy.Hide();
                   MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   SetLog(txtLog, "\r\n生成省台预报员排名数据出错【" + DateTime.Now.ToString() + "】\r\n");
                   SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
                   SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
               }
           }

       }

       public static void ImportIndividualRankData(int BeginYear, int BeginMonth, int EndYear, int EndMonth)
       {
           try
           {
               SetLog(txtLog, "\r\n生成预报员排名数据【" + DateTime.Now.ToString() + "】\r\n");
               Estimate.Reports.AutoImportIndividualRankReportData import = new Estimate.Reports.AutoImportIndividualRankReportData(ConfigurationManager.AppSettings["ConnectionString"]);
               import.AddIndividualRankReportData(BeginYear, BeginMonth, EndYear, EndMonth);
               SetLog(txtLog, "\r\n成功生成预报员排名数据【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
           }
           catch (Exception ex)
           {
               if (ex is ThreadAbortException)
                   SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
               else
               {
                   busy.Hide();
                   MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   SetLog(txtLog, "\r\n生成预报员排名数据出错【" + DateTime.Now.ToString() + "】\r\n");
                   SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
                   SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
               }
           }

       }

       public static void ImportUsuallyReportData(int BeginYear, int BeginMonth, int EndYear, int EndMonth)
       {
           try
           {
               SetLog(txtLog, "\r\n生成常用报表数据【" + DateTime.Now.ToString() + "】\r\n");
               Estimate.Reports.AutoImporttUsuallyReportData import = new Estimate.Reports.AutoImporttUsuallyReportData(ConfigurationManager.AppSettings["ConnectionString"]);
               import.AddUsuallyReportData(BeginYear, BeginMonth, EndYear, EndMonth);
               SetLog(txtLog, "\r\n成功生成常用报表数据【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
           }
           catch (Exception ex)
           {
               if (ex is ThreadAbortException)
                   SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
               else
               {
                   busy.Hide();
                   MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   SetLog(txtLog, "\r\n生成常用报表数据出错【" + DateTime.Now.ToString() + "】\r\n");
                   SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
                   SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
               }
           }

       }

       public static void ImportZytHandinReportData(int BeginYear, int BeginMonth, int EndYear, int EndMonth, ZytHandinReportType type,string reportName)
       {
           try
           {
               SetLog(txtLog, "\r\n生成" + reportName + "核查表数据【" + DateTime.Now.ToString() + "】\r\n");
               Estimate.Reports.AutoImportZytHandinReportData import = new Estimate.Reports.AutoImportZytHandinReportData(ConfigurationManager.AppSettings["ConnectionString"]);
               import.AddZytHandinReportData(BeginYear, BeginMonth, EndYear, EndMonth, type);
               SetLog(txtLog, "\r\n成功生成" + reportName + "核查表数据【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
           }
           catch (Exception ex)
           {
               if (ex is ThreadAbortException)
                   SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
               else
               {
                   if (ex is ThreadAbortException)
                       SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
                   else
                   {
                       busy.Hide();
                       MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                       SetLog(txtLog, "\r\n生成" + reportName + "核查表数据出错【" + DateTime.Now.ToString() + "】\r\n");
                       SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
                       SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
                   }
               }
           }


       }

       public static void ImportCollectionRankReportData(int BeginYear, int BeginMonth, int EndYear, int EndMonth)
       {
           try
           {
               SetLog(txtLog, "\r\n生成台站排名表数据【" + DateTime.Now.ToString() + "】\r\n");
               Estimate.Reports.AutoImportCollectionRankReportData import = new Estimate.Reports.AutoImportCollectionRankReportData(ConfigurationManager.AppSettings["ConnectionString"]);
               import.AddCollectionRankReportData(BeginYear, BeginMonth, EndYear, EndMonth);
               SetLog(txtLog, "\r\n成功生成台站排名表数据【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
           }
           catch (Exception ex)
           {
               if (ex is ThreadAbortException)
                   SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
               else
               {
                   if (ex is ThreadAbortException)
                       SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
                   else
                   {
                       busy.Hide();
                       MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                       SetLog(txtLog, "\r\n生成台站排名表数据出错【" + DateTime.Now.ToString() + "】\r\n");
                       SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
                       SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
                   }
               }

           }
       }

       public static void BuildOptimalForeData(DateTime beginDate, DateTime endDate)
       {
           try
           {
               DataImporterCombiner combiner = new DataImporterCombiner(ConfigurationManager.AppSettings);
               combiner.Log = OperateTools.Log;

               SetLog(txtLog, "\r\n生成新的预报产品数据【" + beginDate.ToString() + "】\r\n");

               DateTime currentDate = beginDate;
               while (currentDate <= endDate)
               {
                   combiner.ImportNewForeData(ConfigurationManager.AppSettings["ConnectionString"], currentDate, Application.StartupPath);

                   currentDate = currentDate.AddDays(1);
               }

               SetLog(txtLog, "\r\n生成最优集成预报数据【" + beginDate.ToString() + "】\r\n");

               currentDate = beginDate;
               while (currentDate <= endDate)
               {
                   combiner.ImportOptimalForeData(ConfigurationManager.AppSettings["ConnectionString"], currentDate, Application.StartupPath);

                   currentDate = currentDate.AddDays(1);
               }

               SetLog(txtLog, "\r\n成功生成最优集成预报数据【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
           }
           catch (Exception ex)
           {
               if (ex is ThreadAbortException)
                   SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
               else
               {
                   busy.Hide();
                   MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   SetLog(txtLog, "\r\n生成最优集成预报数据出错【" + DateTime.Now.ToString() + "】\r\n");
                   SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
                   SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
               }
           }
          
       }

       public static void ExportAccuSubjectiveForecastFile(DateTime beginDate, DateTime endDate, ForeSemiType semiType, CollectionRankType collectionRankType, string directory)
       {
           try
           {
               Estimate.Reports.AccuSubjectiveForecastScoreFile ExportSubjectiveForecastScore = new Estimate.Reports.AccuSubjectiveForecastScoreFile(ConfigurationManager.AppSettings["ConnectionString"]);
               while (beginDate <= endDate)
               {
                   SetLog(txtLog, "\r\n导出Accu主观预报评分样本文件【" + beginDate.ToString() + "】\r\n");
                   ExportSubjectiveForecastScore.GetSubjectiveForecastScoreXML(beginDate, semiType, directory, null);

                   beginDate = beginDate.AddDays(1);
               }

               SetLog(txtLog, "\r\n成功导出Accu主观预报评分样本文件【" + DateTime.Now.ToString() + "】\r\n");
               SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
           }
           catch (Exception ex)
           {
               if (ex is ThreadAbortException)
                   SetLog(txtLog, "\r\n程序中止【" + DateTime.Now.ToString() + "】\r\n");
               else
               {
                   busy.Hide();
                   MessageBox.Show(ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   SetLog(txtLog, "\r\n导出Accu主观预报评分样本文件出错【" + DateTime.Now.ToString() + "】\r\n");
                   SetLog(txtLog, "\r\n错误信息：\r\n" + ex.ToString() + "\r\n");
                   SetLog(txtLog, "\r\n====================================================================\r\n\r\n\r\n\r\n");
               }
           }

       }

       static void CreateDirectory(string path)
       {
            string directory = "";
            foreach (string dir in path.Replace("/", "\\").Split('\\'))
           {
               if (dir != "")
               {
                   directory += dir + "\\";
                   if (!Directory.Exists(directory))
                       Directory.CreateDirectory(directory);
               }
           }
       }
    }
}
